import datetime
import logging
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from cars.models import Car
from mgmt import pagination
from mgmt.serializers import SecuritySerl
from persons.models import Person
from persons.serializers import PersonLstSerl
from student.models import StudentInvite
from student.models import StudentModel
from student.models import StudentInviteVerify
from student.models import StudentInvitePerson
from student.serializers import StudentInviteDetSerl
from student.serializers import StudentInvitePersonSerl
from teacher.auth import TeacherJWT
from sms import views as sms_api
from ymiot import views as ymiot_api
from mgmt.models import Security
from visitor.models import VisitorApply
from visitor.models import VisitorApplyCar
from visitor.models import VisitorApplyPerson
from visitor.models import VisitorApplyVerify
from visitor.serializers import VisitorApplyCarSerl
from visitor.serializers import VisitorApplyDetSerl
from visitor.serializers import VisitorApplyLstSerl
from visitor.serializers import VisitorApplyPersonSerl
from visitor.serializers import VisitorApplyVerifySerl
from teacher.models import TeacherCar
from teacher.models import TeacherInvite
from teacher.models import TeacherInviteCar
from teacher.models import TeacherInvitePerson
from teacher.models import TeacherInviteVerify
from teacher.models import TeacherModel
from teacher.models import TeacherPerson
from teacher.serializers import TeacherCarSerl
from teacher.serializers import TeacherInviteCarSerl
from teacher.serializers import TeacherInviteDetSerl
from teacher.serializers import TeacherInvitePersonSerl
from teacher.serializers import TeacherPersonSerl
from teacher.serializers import TeacherSerl


logger = logging.getLogger("log")


class InfoIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        return Response(result)


class TeacherIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        # 我的审核
        verifyInviteList = TeacherInviteVerify.objects.filter(
            teacher=request_teacher, status=0
        )
        result["data"]["verifyCount"] = verifyInviteList.count()
        verifyInviteList = verifyInviteList[:3]
        verifyInviteLst = []
        verifyInviteIdLst = []
        for verifyInviteItem in verifyInviteList:
            verifyInviteIdLst.append(verifyInviteItem.invite.id)
            verifyInviteItm = {}
            verifyInviteItm["id"] = verifyInviteItem.invite.id
            verifyInviteItm["person"] = verifyInviteItem.invite.person.name
            verifyInviteItm["personDept"] = verifyInviteItem.invite.person.dept
            verifyInviteItm["personPhone"] = verifyInviteItem.invite.person.phone
            verifyInviteItm["status"] = verifyInviteItem.invite.status
            verifyInviteItm["statusText"] = verifyInviteItem.invite.get_status_display()
            verifyInviteItm["teacherId"] = verifyInviteItem.invite.teacher.id
            verifyInviteItm["teacherDept"] = verifyInviteItem.invite.teacher.dept
            verifyInviteItm["teacherName"] = verifyInviteItem.invite.teacher.name
            verifyInviteItm["teacherPhone"] = verifyInviteItem.invite.teacher.phone
            verifyInviteItm["when"] = verifyInviteItem.invite.when.strftime(
                "%m-%d %H:%M"
            )
            verifyInviteItm["verifyId"] = verifyInviteItem.id
            verifyInviteLst.append(verifyInviteItm)
        result["data"]["verifyInviteLst"] = verifyInviteLst
        # 我发起的邀约
        teacher_invite_list = TeacherInvite.objects.filter(
            teacher=request_teacher
        ).order_by("-updated")
        result["data"]["inviteCount"] = teacher_invite_list.count()
        teacher_invite_list = teacher_invite_list[:3]
        invite_list = []
        for teacher_invite in teacher_invite_list:
            # if invite_item.id in verifyInviteIdLst:
            #     continue
            invite_item = {}
            invite_item["id"] = teacher_invite.id
            invite_item["person"] = teacher_invite.person.name
            invite_item["personDept"] = teacher_invite.person.dept
            invite_item["personPhone"] = teacher_invite.person.phone
            invite_item["status"] = teacher_invite.status
            invite_item["statusText"] = teacher_invite.get_status_display()
            invite_item["when"] = teacher_invite.when.strftime("%m-%d %H:%M")
            invite_item["teacherId"] = teacher_invite.teacher.id
            invite_item["teacherDept"] = teacher_invite.teacher.dept
            invite_item["teacherName"] = teacher_invite.teacher.name
            invite_item["teacherPhone"] = teacher_invite.teacher.phone
            invite_list.append(invite_item)
        result["data"]["inviteList"] = invite_list
        return Response(result)


class TeacherPersonListApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        teacher_person_list = TeacherPerson.objects.filter(teacher=request.user).order_by("-order")[:5]
        teacherPersonList = []
        for teacher_person in teacher_person_list:
            teacherPersonItem = {}
            teacherPersonItem["id"] = teacher_person.id
            teacherPersonItem["uuid"] = teacher_person.person.uuid
            teacherPersonItem["name"] = teacher_person.person.name
            teacherPersonItem["phone"] = teacher_person.person.phone
            teacherPersonList.append(teacherPersonItem)
        result["data"]["teacherPersonList"] = teacherPersonList
        return Response(result)


class TeacherPersonSearchApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        phone = request.GET.get("phone")
        try:
            person = Person.objects.get(phone=phone)
            result["data"]["oldPerson"] = PersonLstSerl(person).data
        except Person.DoesNotExist:
            result["code"] = 404
            result["msg"] = "未找到该用户"
        return Response(result)


class TeacherPersonAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        dept = request.data["dept"]
        phone = request.data["phone"]
        name = request.data["name"]
        try:
            person = Person.objects.get(phone=phone)
        except Person.DoesNotExist:
            person = Person()
            person.phone = phone
            person.name = name
            person.dept = dept
            person.save()
        if not TeacherPerson.objects.filter(
            teacher=request_teacher, person=person
        ).exists():
            teacher_person = TeacherPerson()
            teacher_person.person = person
            teacher_person.teacher = request_teacher
            teacher_person.save()
        result["data"]["addPerson"] = {
            "uuid": person.uuid,
            "name": person.name,
            "phone": person.phone,
        }
        return Response(result)


class TeacherPersonBindApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        uuid = request.data["uuid"]
        try:
            person = Person.objects.get(uuid=uuid)
        except Person.DoesNotExist:
            result["code"] = 404
            result["msg"] = "未找到该用户"
            return Response(result)
        if not TeacherPerson.objects.filter(
            teacher=request_teacher, person=person
        ).exists():
            teacher_person = TeacherPerson()
            teacher_person.person = person
            teacher_person.teacher = request_teacher
            teacher_person.save()
        result["data"]["bindPerson"] = {
            "uuid": person.uuid,
            "name": person.name,
            "phone": person.phone,
        }
        return Response(result)


class TeacherCarListApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        teacher_car_list = TeacherCar.objects.filter(teacher=request.user).order_by("order")[:5]
        teacherCarList = []
        for teacher_car in teacher_car_list:
            teacherCarItem = {}
            teacherCarItem["id"] = teacher_car.id
            teacherCarItem["carId"] = teacher_car.car.id
            teacherCarItem["plate"] = teacher_car.car.plate
            teacherCarItem["status"] = teacher_car.car.status
            teacherCarList.append(teacherCarItem)
        result["data"]["teacherCarList"] = teacherCarList
        return Response(result)


class TeacherCarSearchApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        plate = request.GET.get("plate")
        try:
            car = Car.objects.get(plate=plate)
        except Car.DoesNotExist:
            car = Car()
            car.plate = plate
            car.save()
        # 绑定
        if not TeacherCar.objects.filter(teacher=request_teacher, car=car).exists():
            teacher_car = TeacherCar()
            teacher_car.car = car
            teacher_car.teacher = request_teacher
            teacher_car.save()
        result["data"]["newCar"] = {
            "id": car.id,
            "plate": car.plate,
            "status": car.status,
            "status_text": car.get_status_display(),
        }
        return Response(result)


class TeacherInviteStatusApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        car_count = request.GET.get("car_count")
        car_count = int(car_count)
        carFlag = 0
        if car_count > 0:
            carFlag = 1
        isfree = request.GET.get("isfree")
        isfree = int(isfree)
        # 安全等级
        security = Security.objects.get(pk=1)
        # 判断状态
        if security.level == 0:
            # 安防等级正常
            if carFlag == 0:
                # 无车辆,下一步直接访问中
                nextDesc = "安防等级正常,无车辆"
                nextStatus = 7
            else:
                # 有车辆
                if isfree == 1:
                    # 免收停车费
                    if request_teacher.is_leader == 1:
                        # 有处长权限,完成审核
                        nextDesc = "安防等级正常,有车辆,免收停车费,有处长权限"
                        nextStatus = 5
                    else:
                        # 无处长权限,下一步上级审核
                        nextDesc = "安防等级正常,有车辆,免收停车费,无处长权限"
                        nextStatus = 1
                else:
                    # 收取停车费
                    nextDesc = "安防等级正常,有车辆,收取停车费"
                    nextStatus = 5
        elif security.level == 1:
            # 安防等级严管
            if carFlag == 0:
                # 无车辆
                if request_teacher.is_security == 1:
                    # 有保卫处权限,下一步直接访问中
                    nextDesc = "安防等级严管,无车辆,有保卫处权限"
                    nextStatus = 7
                else:
                    # 无保卫处权限，交保卫处审核
                    nextDesc = "安防等级严管,无车辆,无保卫处权限"
                    nextStatus = 2
            else:
                # 有车辆
                if isfree == 1:
                    # 免收停车费
                    if request_teacher.is_leader == 1:
                        # 有处长权限
                        if request_teacher.is_security == 1:
                            # 有保卫处权限,完成审核
                            nextDesc = (
                                "安防等级严管,有车辆,免收停车费,有处长权限,有保卫处权限"
                            )
                            nextStatus = 5
                        else:
                            # 无保卫处权限，交保卫处审核
                            nextDesc = (
                                "安防等级严管,有车辆,免收停车费,有处长权限,无保卫处权限"
                            )
                            nextStatus = 2
                    else:
                        # 无处长权限,下一步上级审核
                        nextDesc = "安防等级严管,有车辆,免收停车费,无处长权限"
                        nextStatus = 1
                else:
                    # 收取停车费
                    if request_teacher.is_security == 1:
                        # 有保卫处权限,完成审核
                        nextDesc = "安防等级严管,有车辆,收取停车费,有保卫处权限"
                        nextStatus = 5
                    else:
                        # 无保卫处权限，交保卫处审核
                        nextDesc = "安防等级严管,有车辆,收取停车费,无保卫处权限"
                        nextStatus = 2
        elif security.level == 2:
            # 安防等级关闭
            if request_teacher.is_security == 1:
                # 有保卫处权限
                if carFlag == 1:
                    # 有车辆
                    if isfree == 1:
                        # 免收停车费
                        if request_teacher.is_leader == 1:
                            # 有处长权限,完成审核
                            nextDesc = "安防等级关闭,有车辆,免收停车费,有处长权限"
                            nextStatus = 5
                        else:
                            # 无处长权限,下一步上级审核
                            nextDesc = "安防等级关闭,有车辆,免收停车费,无处长权限"
                            nextStatus = 1
                    else:
                        # 收取停车费，完成审核
                        nextDesc = "安防等级关闭,有车辆,收取停车费,有保卫处权限"
                        nextStatus = 5
                else:
                    # 无车辆
                    nextDesc = "安防等级关闭,有车辆,收取停车费,有保卫处权限"
                    nextStatus = 5
            else:
                # 无保卫处权限，取消访问
                nextDesc = "安防等级关闭,无保卫处权限"
                nextStatus = 10
        result["data"]["nextDesc"] = nextDesc
        result["data"]["nextStatus"] = nextStatus
        # 上级superior
        if nextStatus == 1:
            superior_list = TeacherModel.objects.filter(
                dept=request_teacher.dept, is_leader=1
            )
            result["data"]["supLst"] = TeacherSerl(superior_list, many=True).data
        # 保卫处
        if nextStatus == 2:
            security_list = TeacherModel.objects.filter(is_security=1)
            result["data"]["secLst"] = TeacherSerl(security_list, many=True).data
        return Response(result)


class TeacherInviteAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        when = request.data["when"]
        what = request.data["what"]
        isfree = request.data["isfree"]
        isfree = int(isfree)
        # # 判断车辆是否已经入场
        # carFlag = 0
        # try:
        #     carLst = request.data["carLst"]
        #     if len(carLst) > 0:
        #         carFlag = 1
        #     for carItm in carLst:
        #         car = Car.objects.get(id=carItm["id"])
        #         if car.status == 3:
        #             msg = "车辆" + car.plate + "已在场内，无法再次申请"
        #             ret = {"code": 500, "msg": msg}
        #             return Response(ret)
        # except Exception:
        #     pass
        next_desc = request.data["next_desc"]
        next_status = request.data["next_status"]
        supid = request.data["supid"]
        secid = request.data["secid"]
        person_list = request.data["person_list"]
        car_list = request.data["car_list"]
        # 找到main_person
        main_person = Person.objects.get(uuid=person_list[0]["uuid"])
        # 创建申请
        invite = TeacherInvite()
        invite.person = main_person
        invite.teacher = request_teacher
        invite.when = when
        invite.what = what
        invite.isfree = isfree
        invite.status = next_status
        invite.save()
        # 2.处理人员
        for person_item in person_list:
            person = Person.objects.get(uuid=person_item["uuid"])
            # 2.1 加入申请
            if not TeacherInvitePerson.objects.filter(
                invite=invite, person=person
            ).exists():
                teacher_invite_person = TeacherInvitePerson()
                teacher_invite_person.invite = invite
                teacher_invite_person.person = person
                teacher_invite_person.save()
            # 2.2 处理人员状态
            person.status = 2
            person.save()
            # 2.3 处理人员绑定
            if not TeacherPerson.objects.filter(
                teacher=request_teacher, person=person
            ).exists():
                teacher_person = TeacherPerson()
                teacher_person.person = person
                teacher_person.teacher = request_teacher
                teacher_person.save()
            else:
                teacher_person = TeacherPerson.objects.filter(
                    teacher=request_teacher, person=person
                ).last()
            # 2.4 增加order
            teacher_person.order = teacher_person.order + 1
            teacher_person.save()
        # 3.处理车辆
        for car_item in car_list:
            car = Car.objects.get(id=car_item["id"])
            # 3.1 加入申请
            if not TeacherInviteCar.objects.filter(invite=invite, car=car).exists():
                teacher_invite_car = TeacherInviteCar()
                teacher_invite_car.invite = invite
                teacher_invite_car.car = car
                teacher_invite_car.save()
            # 3.2 处理车辆状态
            car.status = 2
            car.save()
            # 3.3 处理车辆绑定
            if not TeacherCar.objects.filter(teacher=request_teacher, car=car).exists():
                teacher_car = TeacherCar()
                teacher_car.car = car
                teacher_car.teacher = request_teacher
                teacher_car.save()
            else:
                teacher_car = TeacherCar.objects.filter(
                    teacher=request_teacher, car=car
                ).last()
            # 3.4 增加车辆order
            teacher_car.order = teacher_car.order + 1
            teacher_car.save()
        # 处理申请审核
        if next_status == 1:
            sup = TeacherModel.objects.get(id=supid)
            teacher_invite_verify = TeacherInviteVerify()
            teacher_invite_verify.stage = 1
            teacher_invite_verify.invite = invite
            teacher_invite_verify.teacher = sup
            teacher_invite_verify.describe = next_desc
            teacher_invite_verify.save()
            # 处理短信
            smsvars = {
                'source': '教师{}'.format(request_teacher.name),
            }
            sms_api.send_sms(1, sup.phone, smsvars)
        elif next_status == 2:
            sec = TeacherModel.objects.get(id=secid)
            teacher_invite_verify = TeacherInviteVerify()
            teacher_invite_verify.stage = 2
            teacher_invite_verify.invite = invite
            teacher_invite_verify.teacher = sec
            teacher_invite_verify.describe = next_desc
            teacher_invite_verify.save()
            # 处理短信
            smsvars = {
                'source': '教师{}'.format(request_teacher.name),
            }
            sms_api.send_sms(1, sec.phone, smsvars)
        # 处理通过车辆
        if invite.status == 5:
            teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=invite)
            for teacher_invite_car in teacher_invite_car_list:
                car = teacher_invite_car.car
                invitewhen = invite.when
                print(type(invitewhen))
                print(invitewhen)
                invitewhen = invitewhen + ":00"
                invitewhen = datetime.datetime.strptime(invitewhen, "%Y-%m-%d %H:%M:%S")
                print(type(invitewhen))
                print(invitewhen)
                beginTime = invitewhen - datetime.timedelta(hours=1)
                now = datetime.datetime.now()
                if beginTime < now:
                    beginTimeTxt = (now + datetime.timedelta(minutes=5)).strftime(
                        "%Y-%m-%d %H:%M:%S"
                    )
                else:
                    beginTimeTxt = beginTime.strftime("%Y-%m-%d %H:%M:%S")
                endTimeTxt = invitewhen.replace(hour=23, minute=59, second=59).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                response_add = ymiot_api.add_visitor_car(
                    car.plate, beginTimeTxt, endTimeTxt
                )
                if response_add["code"] == 0:
                    response_data = response_add["data"]
                    response_visitorNo = response_data["visitorNo"]
                    response_beginTime = response_data["beginTime"]
                    response_endTime = response_data["endTime"]
                    car.status = 2
                    car.visitor_no = response_visitorNo
                    car.begin_time = response_beginTime
                    car.end_time = response_endTime
                    car.enter_time = None
                    car.enter_gate_name = None
                    car.out_time = None
                    car.out_gate_name = None
                    car.save()
                    # 处理车辆日志
                    # logName = f"<教师>{requestTeacher.name}"
                    # makeCarLog(car.id, logName, "访客车辆状态添加成功")
                    # 处理短信
                    smsvars = {
                        "role": invite.person.name + "访客",
                        "plate": car.plate,
                        "time1": car.begin_time,
                    }
                    sms_api.send_sms(2, invite.person.phone, smsvars)
                else:
                    print(response_add["msg"])
        return Response(result)


class TeacherInviteLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        # 申请
        inviteList = TeacherInvite.objects.filter(teacher=request_teacher).order_by(
            "-updated"
        )
        inviteLst = []
        for invite in inviteList:
            inviteItm = {}
            inviteItm["id"] = invite.id
            inviteItm["person"] = invite.person.name
            inviteItm["personDept"] = invite.person.dept
            inviteItm["personPhone"] = invite.person.phone
            inviteItm["status"] = invite.status
            inviteItm["statusText"] = invite.get_status_display()
            inviteItm["when"] = invite.when.strftime("%m-%d %H:%M")
            inviteItm["teacherid"] = invite.teacher.id
            inviteItm["teacherDept"] = invite.teacher.dept
            inviteItm["teacherName"] = invite.teacher.name
            inviteItm["teacherPhone"] = invite.teacher.phone
            inviteLst.append(inviteItm)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(inviteLst, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class TeacherInviteDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        # 安全等级
        security = Security.objects.get(pk=1)
        # 申请详情
        invite_id = request.GET.get("invite_id")
        invite = TeacherInvite.objects.get(id=invite_id)
        result["data"]["invite"] = TeacherInviteDetSerl(invite).data
        main_person = invite.person
        result["data"]["mainPerson"] = PersonLstSerl(main_person).data
        teacher_invite_person_list = TeacherInvitePerson.objects.filter(
            invite=invite
        ).exclude(person=main_person)
        if teacher_invite_person_list.count() == 0:
            result["data"]["invitePersonFlag"] = 0
        else:
            result["data"]["invitePersonFlag"] = 1
            result["data"]["invitePersonList"] = TeacherInvitePersonSerl(
                teacher_invite_person_list, many=True
            ).data
        # 处理车辆
        teacher_invite_car_list = TeacherInviteCar.objects.filter(invite=invite)
        if teacher_invite_car_list.count() == 0:
            inviteCarFlag = 0
            result["data"]["inviteCarFlag"] = 0
        else:
            inviteCarFlag = 1
            result["data"]["inviteCarFlag"] = inviteCarFlag
            result["data"]["inviteCarList"] = TeacherInviteCarSerl(
                teacher_invite_car_list, many=True
            ).data
        #  处理随行人员
        # 预处理下一步
        STATUS_CHOISE = (
            (0, "被访者审核"),
            (1, "上级审核"),
            (2, "保卫处审核"),
            (5, "同意访问"),
            (6, "拒绝访问"),
            (7, "访问中"),
            (8, "完成访问"),
            (9, "访问过期"),
            (10, "访客取消"),
        )
        next_desc = ""
        next_status = 0
        if invite.status == 1:
            # 处长审核中
            if security.level == 0:
                # 安防等级正常,完成审核
                next_desc = "安防等级正常,处长审核"
                next_status = 5
            elif security.level == 1:
                # 安防等级严管
                if request_teacher.is_security == 1:
                    # 有保卫处权限,下一步直接访问中
                    next_desc = "安防等级严管,处长审核,有保卫处权限"
                    next_status = 5
                else:
                    # 无保卫处权限，交保卫处审核
                    next_desc = "安防等级严管,处长审核,无保卫处权限"
                    next_status = 2
            elif security.level == 2:
                # 安防等级关闭
                if request_teacher.is_security == 1:
                    # 有保卫处权限,下一步直接访问中
                    next_desc = "安防等级关闭,处长审核,有保卫处权限"
                    next_status = 5
                else:
                    # 无保卫处权限，交保卫处审核
                    next_desc = "安防等级关闭,处长审核,无保卫处权限"
                    next_status = 2
        elif invite.status == 2:
            # 保卫处审核
            next_desc = "保卫处审核,同意后可访问"
            next_status = 5
        result["data"]["nextDesc"] = next_desc
        result["data"]["nextStatus"] = next_status
        # 保卫处
        if next_status == 2:
            security_list = TeacherModel.objects.filter(is_security=1)
            result["data"]["secLst"] = TeacherSerl(security_list, many=True).data
        # 审核列表
        teacher_invite_verify_list = (
            TeacherInviteVerify.objects.filter(invite=invite)
            .exclude(status=0)
            .order_by("-updated")
        )
        invite_verify_list = []
        for teacher_invite_verify in teacher_invite_verify_list:
            invite_verify_item = {}
            invite_verify_item["id"] = teacher_invite_verify.id
            invite_verify_item["status"] = teacher_invite_verify.status
            invite_verify_item["statusText"] = (
                teacher_invite_verify.get_status_display()
            )
            invite_verify_item["stage"] = teacher_invite_verify.stage
            invite_verify_item["stageText"] = teacher_invite_verify.get_stage_display()
            invite_verify_item["teachername"] = teacher_invite_verify.teacher.name
            invite_verify_item["describe"] = teacher_invite_verify.describe
            invite_verify_item["updated"] = teacher_invite_verify.updated.strftime(
                "%m-%d %H:%M"
            )
            invite_verify_list.append(invite_verify_item)
        result["data"]["verifyLst"] = invite_verify_list
        return Response(result)


class TeacherInviteApproveApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        print("访客申请审核通过")
        inviteId = request.data["inviteId"]
        print("inviteId", inviteId)
        invite = TeacherInvite.objects.get(id=inviteId)
        verifyId = request.data["verifyId"]
        print("verifyId", verifyId)
        inviteVerify = TeacherInviteVerify.objects.get(id=verifyId)
        nextDesc = request.data["nextDesc"]
        print("nextDesc", nextDesc)
        nextStatus = request.data["nextStatus"]
        print("nextStatus", nextStatus)
        secId = request.data["secId"]
        print("secId", secId)
        # 处理申请
        invite.status = nextStatus
        invite.save()
        # 处理审核记录
        inviteVerify.status = 1
        inviteVerify.describe = "<通过审核>" + nextDesc
        inviteVerify.save()
        if nextStatus == 2:
            # 保卫处审核中
            # 创建新审核记录
            sec = TeacherModel.objects.get(id=secId)
            newVerify = TeacherInviteVerify()
            newVerify.invite = invite
            newVerify.status = 0
            newVerify.stage = 2
            newVerify.teacher = sec
            newVerify.save()
            # 处理短信
            smsvars = {
                'source': '教师{}'.format(request_teacher.name),
            }
            sms_api.send_sms(1, sec.phone, smsvars)
        # 处理通过车辆
        if invite.status == 5:
            inviteCarLst = TeacherInviteCar.objects.filter(invite=invite)
            for inviteCar in inviteCarLst:
                car = inviteCar.car
                when = invite.when
                beginTime = when - datetime.timedelta(hours=1)
                now = datetime.datetime.now()
                if beginTime < now:
                    beginTimeTxt = (now + datetime.timedelta(minutes=5)).strftime(
                        "%Y-%m-%d %H:%M:%S"
                    )
                else:
                    beginTimeTxt = beginTime.strftime("%Y-%m-%d %H:%M:%S")
                endTimeTxt = when.replace(hour=23, minute=59, second=59).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                response_add = ymiot_api.add_visitor_car(
                    car.plate, beginTimeTxt, endTimeTxt
                )
                if response_add["code"] == 0:
                    response_data = response_add["data"]
                    response_visitorNo = response_data["visitorNo"]
                    response_beginTime = response_data["beginTime"]
                    response_endTime = response_data["endTime"]
                    car.status = 2
                    car.visitor_no = response_visitorNo
                    car.begin_time = response_beginTime
                    car.end_time = response_endTime
                    car.enter_time = None
                    car.enter_gate_name = None
                    car.out_time = None
                    car.out_gate_name = None
                    car.save()
                    # 处理车辆日志
                    # logName = f"<教师>{requestTeacher.name}"
                    # makeCarLog(car.id, logName, "访客车辆状态添加成功")
                    # 处理短信
                    smsvars = {
                        "role": invite.person.name + "访客",
                        "plate": car.plate,
                        "time1": car.begin_time,
                    }
                    sms_api.send_sms(2, invite.person.phone, smsvars)
                else:
                    print(response_add["msg"])
        result["data"]["invite"] = TeacherInviteDetSerl(invite).data
        return Response(result)


class TeacherInviteDenialApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        print("访客申请审核拒绝")
        inviteId = request.data["inviteId"]
        print("inviteId", inviteId)
        invite = TeacherInvite.objects.get(id=inviteId)
        verifyId = request.data["verifyId"]
        print("verifyId", verifyId)
        inviteVerify = TeacherInviteVerify.objects.get(id=verifyId)
        nextDesc = request.data["nextDesc"]
        print("nextDesc", nextDesc)
        # 处理申请
        invite.status = 6
        invite.save()
        # 处理审核记录
        inviteVerify.status = 2
        inviteVerify.describe = "<审核拒绝>" + nextDesc
        inviteVerify.save()
        return Response(result)


class VisitorIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        # 我的审核
        visitor_apply_verify_list = VisitorApplyVerify.objects.filter(
            teacher=request_teacher, status=0
        ).order_by("-updated")
        result["data"]["verifyCount"] = visitor_apply_verify_list.count()
        visitor_apply_verify_list = visitor_apply_verify_list[:3]
        apply_verify_list = []
        apply_verify_id_list = []
        for visitor_apply_verify in visitor_apply_verify_list:
            if visitor_apply_verify.apply.status == 10:
                continue
            apply_verify_id_list.append(visitor_apply_verify.apply.id)
            # apply_verify_item = VisitorApplyVerifySerl(visitor_apply_verify).data
            apply_verify_item = {}
            apply_verify_item["id"] = visitor_apply_verify.apply.id
            apply_verify_item["visitor"] = visitor_apply_verify.apply.visitor.name
            apply_verify_item["visitorDept"] = visitor_apply_verify.apply.visitor.dept
            apply_verify_item["visitorPhone"] = visitor_apply_verify.apply.visitor.phone
            apply_verify_item["status"] = visitor_apply_verify.apply.status
            apply_verify_item["statusText"] = (
                visitor_apply_verify.apply.get_status_display()
            )
            apply_verify_item["when"] = visitor_apply_verify.apply.when.strftime(
                "%m-%d %H:%M"
            )
            apply_verify_item["verifyId"] = visitor_apply_verify.id
            apply_verify_list.append(apply_verify_item)
        result["data"]["applyVerifyLst"] = apply_verify_list
        # 申请
        visitor_apply_list = VisitorApply.objects.filter(
            teacher=request_teacher
        ).order_by("-updated")
        result["data"]["applyCount"] = visitor_apply_list.count()
        visitor_apply_list = visitor_apply_list[:3]
        apply_list = []
        for visitor_apply in visitor_apply_list:
            if visitor_apply.id in apply_verify_id_list:
                continue
            apply_item = VisitorApplyLstSerl(visitor_apply).data
            apply_list.append(apply_item)
        result["data"]["applyLst"] = apply_list
        return Response(result)


class VisitorApplyLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        # 申请
        visitor_apply_list = VisitorApply.objects.filter(
            teacher=request_teacher
        ).order_by("-updated")
        apply_list = []
        for visitor_apply in visitor_apply_list:
            apply_item = {}
            apply_item["id"] = visitor_apply.id
            apply_item["visitor"] = visitor_apply.visitor.name
            apply_item["visitorDept"] = visitor_apply.visitor.dept
            apply_item["visitorPhone"] = visitor_apply.visitor.phone
            apply_item["status"] = visitor_apply.status
            apply_item["statusText"] = visitor_apply.get_status_display()
            apply_item["when"] = visitor_apply.when.strftime("%m-%d %H:%M")
            apply_item["teacherId"] = visitor_apply.teacher.id
            apply_item["teacherDept"] = visitor_apply.teacher.dept
            apply_item["teacherName"] = visitor_apply.teacher.name
            apply_item["teacherPhone"] = visitor_apply.teacher.phone
            apply_list.append(apply_item)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(apply_list, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class VisitorApplyDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        # 安全等级
        security = Security.objects.get(pk=1)
        # 申请详情
        apply_id = request.GET.get("apply_id")
        apply = VisitorApply.objects.get(id=apply_id)
        result["data"]["apply"] = VisitorApplyDetSerl(apply).data
        #  处理人员
        main_person = Person.objects.get(phone=apply.visitor.phone)
        visitor_apply_person_list = VisitorApplyPerson.objects.filter(
            apply=apply
        ).exclude(person=main_person)
        if visitor_apply_person_list.count() == 0:
            result["data"]["applyPersonFlag"] = 0
        else:
            result["data"]["applyPersonFlag"] = 1
            result["data"]["applyPersonList"] = VisitorApplyPersonSerl(
                visitor_apply_person_list, many=True
            ).data
        # 处理车辆
        visitor_apply_car_list = VisitorApplyCar.objects.filter(apply=apply)
        if visitor_apply_car_list.count() == 0:
            applyCarFlag = 0
            result["data"]["applyCarFlag"] = 0
        else:
            applyCarFlag = 1
            result["data"]["applyCarFlag"] = applyCarFlag
            result["data"]["applyCarList"] = VisitorApplyCarSerl(
                visitor_apply_car_list, many=True
            ).data
        # 预处理下一步
        STATUS_CHOISE = (
            (0, "被访者审核"),
            (1, "上级审核"),
            (2, "保卫处审核"),
            (5, "同意访问"),
            (6, "拒绝访问"),
            (7, "访问中"),
            (8, "完成访问"),
            (9, "访问过期"),
            (10, "访客取消"),
        )
        next_desc = ""
        next_status = 0
        if apply.status == 0:
            # 被访者审核中
            if security.level == 0:
                # 安防等级正常
                if applyCarFlag == 1:
                    # 存在访客车辆
                    if apply.isfree == 1:
                        # 免收停车费
                        if request_teacher.is_leader == 1:
                            # 处长权限,同意后完成审核
                            next_desc = "被访者审核,安防等级正常,存在访客车辆,免收停车费,审核者有处长权限"
                            next_status = 5
                        else:
                            # 非处长权限，同意后交由上级审核
                            next_desc = "被访者审核,安防等级正常,存在访客车辆,免收停车费,审核者无处长权限"
                            next_status = 1
                    else:
                        # 收取停车费,同意后完成审核
                        next_desc = "被访者审核,安防等级正常,存在访客车辆,收取停车费"
                        next_status = 5
                else:
                    # 无访客车辆,同意后进行访问
                    next_desc = "被访者审核,安防等级正常,无访客车辆"
                    next_status = 7
            elif security.level == 1:
                # 安防等级严管中
                if applyCarFlag == 1:
                    # 存在访客车辆
                    if apply.isfree == 1:
                        # 免收停车费
                        if request_teacher.is_leader == 1:
                            # 处长权限
                            if request_teacher.is_security == 1:
                                # 保卫处权限,同意后完成审核
                                next_desc = "被访者审核,安防等级严管中,存在访客车辆,免收停车费,审核者有处长权限,审核者有保卫处权限"
                                next_status = 5
                            else:
                                # 非保卫处权限,同意后交由保卫处审核
                                next_desc = "被访者审核,安防等级严管中,存在访客车辆,免收停车费,审核者有处长权限,审核者无保卫处权限"
                                next_status = 2
                        else:
                            # 非处长权限,同意后交由上级审核
                            next_desc = "被访者审核,安防等级严管中,存在访客车辆,免收停车费,审核者无处长权限"
                            next_status = 1
                    else:
                        # 收取停车费
                        if request_teacher.is_security == 1:
                            # 保卫处权限,同意后完成审核
                            next_desc = "被访者审核,安防等级严管中,存在访客车辆,收取停车费,审核者有保卫处权限"
                            next_status = 5
                        else:
                            # 非保卫处权限,同意后交由保卫处审核
                            next_desc = "被访者审核,安防等级严管中,存在访客车辆,收取停车费,审核者无保卫处权限"
                            next_status = 2
                else:
                    # 无访客车辆,同意后交由安保部审核
                    next_desc = "被访者审核,安防等级严管中,无访客车辆"
                    next_status = 2
        elif apply.status == 1:
            # 处长审核中
            if security.level == 0:
                # 安防等级正常,同意后完成审核
                next_desc = "处长审核,安防等级正常"
                next_status = 5
            elif security.level == 1:
                # 安防等级严管中
                if request_teacher.is_security == 1:
                    # 保卫处权限,同意后完成审核
                    next_desc = "处长审核,安防等级严管中,审核者有保卫处权限"
                    next_status = 5
                else:
                    # 非保卫处权限,同意后交由保卫处审核
                    next_desc = "处长审核,安防等级严管中,审核者无保卫处权限"
                    next_status = 2
        elif apply.status == 2:
            # 保卫处审核中,同意后完成审核
            next_desc = "保卫处审核"
            next_status = 5
        result["data"]["nextDesc"] = next_desc
        result["data"]["nextStatus"] = next_status
        # 上级superior
        if next_status == 1:
            superiorLst = TeacherModel.objects.filter(
                dept=request_teacher.dept, is_leader=1
            )
            result["data"]["supLst"] = TeacherSerl(superiorLst, many=True).data
        # 保卫处
        if next_status == 2:
            securityLst = TeacherModel.objects.filter(is_security=1)
            result["data"]["secLst"] = TeacherSerl(securityLst, many=True).data
        # 审核列表
        verifyList = (
            VisitorApplyVerify.objects.filter(apply=apply)
            .exclude(status=0)
            .order_by("-updated")
        )
        verifyLst = []
        for verifyItem in verifyList:
            verifyItm = {}
            verifyItm["id"] = verifyItem.id
            verifyItm["status"] = verifyItem.status
            verifyItm["statusText"] = verifyItem.get_status_display()
            verifyItm["stage"] = verifyItem.stage
            verifyItm["stageText"] = verifyItem.get_stage_display()
            verifyItm["teachername"] = verifyItem.teacher.name
            verifyItm["describe"] = verifyItem.describe
            verifyItm["updated"] = verifyItem.updated.strftime("%m-%d %H:%M")
            verifyLst.append(verifyItm)
        result["data"]["verifyLst"] = verifyLst
        return Response(result)


class VisitorApplyApproveApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        print("访客申请审核通过")
        apply_id = request.data["apply_id"]
        apply = VisitorApply.objects.get(id=apply_id)
        verifyId = request.data["verifyId"]
        print("verifyId", verifyId)
        applyVerify = VisitorApplyVerify.objects.get(id=verifyId)
        desc = request.data["desc"]
        print("desc", desc)
        nextStatus = request.data["nextStatus"]
        print("nextStatus", nextStatus)
        supId = request.data["supId"]
        print("supId", supId)
        secId = request.data["secId"]
        print("secId", secId)
        # 处理申请
        apply.status = nextStatus
        apply.save()
        # 处理审核记录
        applyVerify.status = 1
        applyVerify.describe = "<通过审核>" + desc
        applyVerify.save()
        if nextStatus == 1:
            # 上级审核
            # 创建新审核记录
            sup = TeacherModel.objects.get(id=supId)
            newVerify = VisitorApplyVerify()
            newVerify.apply = apply
            newVerify.status = 0
            newVerify.stage = 1
            newVerify.teacher = sup
            newVerify.save()
            # 处理短信
            smsvars = {
                'source': '教师{}'.format(request_teacher.name),
            }
            sms_api.send_sms(1, sup.phone, smsvars)
        elif nextStatus == 2:
            # 保卫处审核中
            # 创建新审核记录
            sec = TeacherModel.objects.get(id=secId)
            newVerify = VisitorApplyVerify()
            newVerify.apply = apply
            newVerify.status = 0
            newVerify.stage = 2
            newVerify.teacher = sec
            newVerify.save()
            # 处理短信
            smsvars = {
                'source': '教师{}'.format(request_teacher.name),
            }
            sms_api.send_sms(1, sec.phone, smsvars)
        # 处理通过车辆
        if apply.status == 5:
            applyCarLst = VisitorApplyCar.objects.filter(apply=apply)
            for applyCar in applyCarLst:
                car = applyCar.car
                when = apply.when
                beginTime = when - datetime.timedelta(hours=1)
                now = datetime.datetime.now()
                if beginTime < now:
                    beginTimeTxt = (now + datetime.timedelta(minutes=5)).strftime(
                        "%Y-%m-%d %H:%M:%S"
                    )
                else:
                    beginTimeTxt = beginTime.strftime("%Y-%m-%d %H:%M:%S")
                endTimeTxt = when.replace(hour=23, minute=59, second=59).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                response_add = ymiot_api.add_visitor_car(
                    car.plate, beginTimeTxt, endTimeTxt
                )
                if response_add["code"] == 0:
                    response_data = response_add["data"]
                    response_visitorNo = response_data["visitorNo"]
                    response_beginTime = response_data["beginTime"]
                    response_endTime = response_data["endTime"]
                    car.status = 2
                    car.visitor_no = response_visitorNo
                    car.begin_time = response_beginTime
                    car.end_time = response_endTime
                    car.enter_time = None
                    car.enter_gate_name = None
                    car.out_time = None
                    car.out_gate_name = None
                    car.save()
                    # 处理车辆日志
                    # logName = f"<教师>{requestTeacher.name}"
                    # makeCarLog(car.id, logName, "访客车辆状态添加成功")
                    smsvars = {
                        "role": apply.visitor.name + "访客",
                        "plate": car.plate,
                        "time1": car.begin_time
                    }
                    sms_api.send_sms(2, apply.visitor.phone, smsvars)
                else:
                    print(response_add["msg"])
        result["data"]["apply"] = VisitorApplyDetSerl(apply).data
        return Response(result)


class VisitorApplyDenialApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        print("访客申请审核拒绝")
        apply_id = request.data["apply_id"]
        apply = VisitorApply.objects.get(id=apply_id)
        verifyId = request.data["verifyId"]
        print("verifyId", verifyId)
        applyVerify = VisitorApplyVerify.objects.get(id=verifyId)
        desc = request.data["desc"]
        print("desc", desc)
        # 处理申请
        apply.status = 6
        apply.save()
        # 处理审核记录
        applyVerify.status = 2
        applyVerify.describe = "<审核拒绝>" + desc
        applyVerify.save()
        return Response(result)


class StudentIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        # 我的学生
        studentList = StudentModel.objects.filter(dept=request_teacher.dept)
        result["data"]["studentCount"] = studentList.count()
        # 我的审核
        verifyInviteList = StudentInviteVerify.objects.filter(
            teacher=request_teacher, status=0
        ).order_by("-updated")
        result["data"]["verifyCount"] = verifyInviteList.count()
        verifyInviteList = verifyInviteList[:5]
        verifyInviteLst = []
        verifyInviteIdLst = []
        for verifyInviteItem in verifyInviteList:
            verifyInviteIdLst.append(verifyInviteItem.invite.id)
            verifyInviteItm = {}
            verifyInviteItm["id"] = verifyInviteItem.invite.id
            verifyInviteItm["student"] = verifyInviteItem.invite.student.name
            verifyInviteItm["when"] = verifyInviteItem.invite.when.strftime(
                "%m-%d %H:%M"
            )
            verifyInviteItm["status"] = verifyInviteItem.invite.status
            verifyInviteItm["statusText"] = verifyInviteItem.invite.get_status_display()
            verifyInviteItm["verifyId"] = verifyInviteItem.id
            verifyInviteLst.append(verifyInviteItm)
        result["data"]["verifyInviteLst"] = verifyInviteLst
        return Response(result)


class StudentAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        dept = request.data["dept"]
        phone = request.data["phone"]
        name = request.data["name"]
        try:
            student = StudentModel.objects.get(phone=phone)
        except StudentModel.DoesNotExist:
            student = StudentModel()
            student.phone = phone
        student.name = name
        student.dept = dept
        try:
            student.save()
        except Exception as e:
            print(e)
            result["code"] = 500
            result["msg"] = "保存失败"
        return Response(result)


class StudentInviteDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        # 安全等级
        security = Security.objects.get(pk=1)
        # 申请详情
        invite_id = request.GET.get("invite_id")
        invite = StudentInvite.objects.get(id=invite_id)
        result["data"]["invite"] = StudentInviteDetSerl(invite).data
        main_person = invite.person
        result["data"]["mainPerson"] = PersonLstSerl(main_person).data
        #  人员
        student_invite_person_list = StudentInvitePerson.objects.filter(invite=invite)
        if student_invite_person_list.count() == 0:
            result["data"]["invitePersonFlag"] = 0
        else:
            result["data"]["invitePersonFlag"] = 1
            result["data"]["invitePersonList"] = StudentInvitePersonSerl(
                student_invite_person_list, many=True
            ).data
        # 审核列表
        invite_verify_list = (
            StudentInviteVerify.objects.filter(invite=invite)
            .exclude(status=0)
            .order_by("-updated")
        )
        verify_list = []
        for invite_verify in invite_verify_list:
            verify_item = {}
            verify_item["id"] = invite_verify.id
            verify_item["status"] = invite_verify.status
            verify_item["statusText"] = invite_verify.get_status_display()
            verify_item["stage"] = invite_verify.stage
            verify_item["stageText"] = invite_verify.get_stage_display()
            verify_item["teacher"] = invite_verify.teacher.name
            verify_item["describe"] = invite_verify.describe
            verify_item["updated"] = invite_verify.updated.strftime("%m-%d %H:%M")
            verify_list.append(verify_item)
        result["data"]["verifyList"] = verify_list
        # 预处理下一步
        nextDesc = ""
        nextStatus = 0
        if security.level == 0:
            # 安防等级正常,完成审核
            nextDesc = "安防等级正常,可以批准"
            nextStatus = 1
        elif security.level > 1:
            # 安防等级严管
            nextDesc = "安防等级严管,无法批准"
            nextStatus = 0
        result["data"]["nextDesc"] = nextDesc
        result["data"]["nextStatus"] = nextStatus
        return Response(result)


class StudentInviteApproveApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        print("访客申请审核通过")
        invite_id = request.data["invite_id"]
        invite = StudentInvite.objects.get(id=invite_id)
        verify_id = request.data["verify_id"]
        inviteVerify = StudentInviteVerify.objects.get(id=verify_id)
        nextDesc = request.data["nextDesc"]
        print("nextDesc", nextDesc)
        # 处理申请
        invite.status = 7
        invite.save()
        # 处理审核记录
        inviteVerify.status = 1
        inviteVerify.describe = "<通过审核>" + nextDesc
        inviteVerify.save()
        # 处理短信
        # smsvars = {
        #     "role": invite.student.name + "同学",
        #     "plate": car.plate,
        #     "time1": car.begin_time.strftime("%m-%d %H:%M"),
        # }
        # sendSms(2, apply.visitor.phone, smsvars1)
        return Response(result)


class StudentInviteDenialApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        print("访客申请审核拒绝")
        invite_id = request.data["invite_id"]
        invite = StudentInvite.objects.get(id=invite_id)
        verify_id = request.data["verify_id"]
        inviteVerify = StudentInviteVerify.objects.get(id=verify_id)
        nextDesc = request.data["nextDesc"]
        print("nextDesc", nextDesc)
        # 处理申请
        invite.status = 6
        invite.save()
        # 处理审核记录
        inviteVerify.status = 2
        inviteVerify.describe = "<审核拒绝>" + nextDesc
        inviteVerify.save()
        return Response(result)
